package middleware

import (
	"api/cache"
	"api/serializer"
	"encoding/json"

	"github.com/gin-gonic/gin"
)

// CurrentUser 获取登录用户
func CurrentUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		//session := sessions.Default(c)
		utoken, _ := c.Cookie("user_token")
		if utoken != "" {
			//user, err := model.GetUser(uid)

			userstr, err := cache.RedisClient.Get(utoken).Result()
			if err == nil {
				var user serializer.User
				json.Unmarshal([]byte(userstr), &user)
				c.Set("user", user)
			}
		}
		c.Next()
	}
}

// AuthRequired 需要登录
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		if user, _ := c.Get("user"); user != nil {
			if _, ok := user.(serializer.User); ok {
				c.Next()
				return
			}
		}

		c.JSON(200, serializer.CheckLogin())
		c.Abort()
	}
}
